package com.ziyun.erp.modules.suppOffline.service.impl;

import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.suppOffline.ErpSupplierStateEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.modules.freightages.entity.SdbEctoolsRegionsEntity;
import com.ziyun.erp.modules.freightages.service.SdbEctoolsRegionsService;
import com.ziyun.erp.modules.suppOffline.dto.SupplierAuditDto;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.suppOffline.dao.ErpSupplierOfflineDao;
import com.ziyun.erp.modules.suppOffline.entity.ErpSupplierOfflineEntity;
import com.ziyun.erp.modules.suppOffline.service.ErpSupplierOfflineService;


@Service("erpSupplierOfflineService")
public class ErpSupplierOfflineServiceImpl extends ServiceImpl<ErpSupplierOfflineDao, ErpSupplierOfflineEntity> implements ErpSupplierOfflineService {

    @Autowired
    private SdbEctoolsRegionsService sdbEctoolsRegionsService;

    @Override
    public R queryPageErpSupplierList(Map<String, Object> params) {
        String supplierName = (String) params.get("supplierName");
        String state = (String) params.get("state");
        String contactName = (String) params.get("contactName");

        Page<ErpSupplierOfflineEntity> page = this.selectPage(
                new Query<ErpSupplierOfflineEntity>(params).getPage(),
                new EntityWrapper<ErpSupplierOfflineEntity>()
                        .like(StringUtils.isNotBlank(supplierName), "supplier_name", supplierName)
                        .like(StringUtils.isNotBlank(contactName), "contact_name", contactName)
                        .eq(StringUtils.isNotBlank(state), "state", state)
                        .eq("`delete`", DeleteEnum.NOT_DELETE.toInt())
                        .orderBy("create_time", false)

        );
        PageUtils pageUtils = new PageUtils(page);

        // 查询省市区级联数据
        List<String> regions = sdbEctoolsRegionsService.queryRegionsSascade();

        // 存放枚举类到userdata
        Map<String, Object> userDataMap = new HashMap<>();
        userDataMap.put("erpSupplierStateEnum", JsonUtils.enumToList(ErpSupplierStateEnum.class));
        userDataMap.put("regions", JSONArray.fromObject(regions).toString());

        return R.ok().put("page", pageUtils)
                .put("userData", userDataMap);
    }

    @Override
    public R audit(SupplierAuditDto supplierAuditDto) {
        Integer supplierId = supplierAuditDto.getSupplierId();
        ErpSupplierOfflineEntity erpSupplierOffline = this.baseMapper.selectById(supplierId);
        if (erpSupplierOffline.getState().intValue() == ErpSupplierStateEnum.IS_AUDITED.toInt()){
            return R.error("重复审核");
        }

        Integer state = supplierAuditDto.getState();
        String auditName = supplierAuditDto.getAuditName();
        String remarksText = supplierAuditDto.getRemarksText();
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("state", state);
        updateMap.put("remarksText", remarksText);
        updateMap.put("auditName", auditName);
        updateMap.put("auditTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        this.baseMapper.updateByMap(updateMap, supplierId);

        return R.ok();
    }

    @Override
    public R info(Integer supplierId) {
        ErpSupplierOfflineEntity erpSupplierOffline = this.baseMapper.selectById(supplierId);
        String contactAreaId = erpSupplierOffline.getContactAreaId();
        if (StringUtils.isNotBlank(contactAreaId)){
            SdbEctoolsRegionsEntity sdbEctoolsRegions = sdbEctoolsRegionsService.selectInfoById(contactAreaId);
            erpSupplierOffline.setRegionPath(sdbEctoolsRegions.getRegionPath());
        }

        return R.ok().put("erpSupplierOffline", erpSupplierOffline);
    }

    @Override
    public boolean deleteInfoById(List<Integer> ids, Long userId) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("delete", DeleteEnum.DELETE.toInt());
        updateMap.put("updateName", userId);
        updateMap.put("updateTime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        this.baseMapper.updateBatchByMap(updateMap, ids);
        return true;
    }

    @Override
    public void saveInfo(ErpSupplierOfflineEntity erpSupplierOffline, Long userId) {
        String supplierName = erpSupplierOffline.getSupplierName();
        int count = this.selectCount(new EntityWrapper<>(new ErpSupplierOfflineEntity())
                .eq("supplier_name", supplierName)
                .eq("`delete`", DeleteEnum.NOT_DELETE.toInt())
        );
        if (count > 0){
            throw new RRException("外协商名称已存在");
        }
        erpSupplierOffline.setCreateName(userId.toString());
        erpSupplierOffline.setState(ErpSupplierStateEnum.IS_AUDITED.toInt());
        this.insert(erpSupplierOffline);
    }

    @Override
    public void updateInfo(ErpSupplierOfflineEntity erpSupplierOffline, Long userId) {
        Integer supplierId = erpSupplierOffline.getSupplierId();
        String supplierName = erpSupplierOffline.getSupplierName();
        int count = this.selectCount(new EntityWrapper<>(new ErpSupplierOfflineEntity())
                .eq("supplier_name", supplierName)
                .eq("`delete`", DeleteEnum.NOT_DELETE.toInt())
                .ne("supplier_id", supplierId)
        );
        if (count > 0){
            throw new RRException("外协商名称已存在");
        }

        erpSupplierOffline.setUpdateName(userId.toString());
        erpSupplierOffline.setUpdateTime(new Date());
        this.updateById(erpSupplierOffline);
    }

}
